package com.chudy.visual.server.websocket;

import java.util.Objects;

import com.chudy.visual.server.model.ScDevice;
import com.chudy.visual.server.service.ScDeviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.Tio;
import org.tio.core.ChannelContext;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.common.WsSessionContext;
import org.tio.websocket.server.handler.IWsMsgHandler;

/**
 * @author owes
 */
public class VisualWsMsgHandler implements IWsMsgHandler {
	private static Logger log = LoggerFactory.getLogger(VisualWsMsgHandler.class);

	public static final VisualWsMsgHandler me = new VisualWsMsgHandler();
	private static ScDevice dao = new ScDevice().dao();

	private VisualWsMsgHandler() {

	}

	/**
	 * 握手时走这个方法，业务可以在这里获取cookie，request参数�?
	 */
	public HttpResponse handshake(HttpRequest request, HttpResponse httpResponse, ChannelContext channelContext)
			throws Exception {
		String clientip = request.getClientIp();
		String deviceid = request.getParam("deviceid");
		String userid = request.getParam("userid");

		System.out.println("*******************************");
		System.out.println("userid=" + userid);
		System.out.println("deviceid=" + deviceid);
		channelContext.setUserid(userid);
		channelContext.setBsId(deviceid);
		channelContext.setAttribute("clientid", deviceid);
		Tio.bindUser(channelContext, deviceid);
		log.info("收到来自{}的ws握手包\r\n{}", clientip, request.toString());
		return httpResponse;
	}

	/**
	 * @param httpRequest
	 * @param httpResponse
	 * @param channelContext
	 * @throws Exception
	 * @author tanyaowu
	 */
	public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext)
			throws Exception {
		// 绑定到群组，后面会有群发
		String utype = httpRequest.getParam("utype");
		if ("mgr".equals(utype)) {
			Tio.bindGroup(channelContext, Const.GROUP_MGR_ID);
		} else if ("Visual".equals(utype)) {
			Tio.bindGroup(channelContext, Const.GROUP_DEVICE_ID);
		}

		// 更新设备在线状态 为 在线 1
		try {
			String deviceid = httpRequest.getParam("deviceid");
			new ScDeviceService().updateOnlineStatus(deviceid, 1);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		// 客户端握手完成后，推送给管理端，提示设备上线
		int count = Tio.getAllChannelContexts(channelContext.groupContext).getObj().size();
		String msg = "{name:'admin',message:'" + channelContext.userid + " 进来了，共�?" + count + "】人在线" + "'}";
		// 设备上线通知 管理端 广播给所有注册为管理组的用户
		WsResponse wsResponse = WsResponse.fromText(msg, VisualServerConfig.CHARSET);
		Tio.sendToGroup(channelContext.groupContext, Const.GROUP_MGR_ID, wsResponse);
	}

	/**
	 * 字节消息（binaryType = arraybuffer）过来后会走这个方法
	 */
	public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
		return null;
	}

	/**
	 * 当客户端发close flag时，会走这个方法
	 */
	public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
		Tio.remove(channelContext, "receive close flag");
		try {
			String deviceid =channelContext.getBsId();
			new ScDeviceService().updateOnlineStatus(deviceid, 0);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		return null;
	}

	/*
	 * 字符消息（binaryType = blob）过来后会走这个方法
	 */
	public Object onText(WsRequest wsRequest, String text, ChannelContext channelContext) throws Exception {
		WsSessionContext wsSessionContext = (WsSessionContext) channelContext.getAttribute();
		HttpRequest httpRequest = wsSessionContext.getHandshakeRequest();// 获取websocket握手�?
		if (log.isDebugEnabled()) {
			log.debug("握手{}", httpRequest);
		}

		log.info("收到ws消息:{}", text);

		if ("<#heartbeat#>".equalsIgnoreCase(text)) {
			return null;
		}
		// channelContext.getToken()
		// String msg = channelContext.getClientNode().toString() + " 说：" + text;
		// String msg = "{name:'" + channelContext.userid + "',message:'" + text + "'}";
		// 用tio-websocket，服务器发�?到客户端的Packet都是WsResponse
		// WsResponse wsResponse = WsResponse.fromText(msg, VisualServerConfig.CHARSET);
		// 群发
		// Tio.sendToGroup(channelContext.groupContext, Const.GROUP_ID, wsResponse);

		// 返回值是要发送给客户端的内容，一般都是返回null
		return null;
	}
}
